package yagwl.client.view.demo;

import yagwl.client.model.fnd.SessionCache;
import yagwl.client.model.fnd.SessionDto;
import yagwl.client.resource.Resources;
import yagwl.client.view.fnd.BrowserUtil;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class GlobalHeader extends Composite {

  private FlexTable rootFT = new FlexTable();
  private String homePage = "/yagwl.html";

  public GlobalHeader() {
    final SessionDto ses = SessionCache.getInstance().getSession();

    HorizontalPanel hPanel = new HorizontalPanel();
    Label l = new Label(ses.isUserLoggedIn() ? ses.getEmail() : "Welcome Guest");
    hPanel.add(l);
    hPanel.setCellVerticalAlignment(l, HasVerticalAlignment.ALIGN_MIDDLE);
    addSeparator(hPanel);
    // ll.addWidget(new Anchor("Project Home",
    // "http://code.google.com/p/yagwl/",
    // "_blank"));
    hPanel.add(new Anchor("Settings", "https://mail.google.com/mail/#settings",
        "_blank"));
    addSeparator(hPanel);
    if (ses.isUserAdmin()) {
      hPanel.add(new Anchor("Setup", BrowserUtil.resolveHostedHref(homePage),
          "_blank"));
      addSeparator(hPanel);
    }
    if (ses.isUserLoggedIn())
      hPanel.add(new Anchor("Sign Out", BrowserUtil.resolveHostedHref(ses
          .getLogoutURL())));
    else
      hPanel.add(new Anchor("Sign In", BrowserUtil.resolveHostedHref(ses
          .getLoginURL())));

    rootFT.setWidget(0, 0, new Image(Resources.I.logo()));
    rootFT.setWidget(0, 1, hPanel);
    rootFT.getCellFormatter().setVerticalAlignment(0, 1,
        HasVerticalAlignment.ALIGN_TOP);
    rootFT.getCellFormatter().setHorizontalAlignment(0, 1,
        HasHorizontalAlignment.ALIGN_RIGHT);
    rootFT.setWidth("100%");

    initWidget(rootFT);
  }

  private void addSeparator(HorizontalPanel hPanel) {
    HTML h = new HTML("&nbsp;|&nbsp;");
    hPanel.add(h);
  }

  // unused
  private class ClonedSeparator extends Widget {
    private Label separator;
    public ClonedSeparator() {
      Element sepClone = DOM.clone(separator.getElement(), true);
      setElement(sepClone);
    }
  }
}